package cn.dansj.common.mail.utils.javamail;

import cn.dansj.common.mail.utils.*;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public interface JavaMailSender extends MailSender {
    MimeMessage createMimeMessage();

    MimeMessage createMimeMessage(InputStream contentStream) throws MailException;

    default void send(MimeMessage mimeMessage) throws MailException {
        send(new MimeMessage[]{mimeMessage});
    }

    void send(MimeMessage... mimeMessages) throws MailException;

    default void send(MimeMessagePreparator mimeMessagePreparator) throws MailException {
        send(new MimeMessagePreparator[]{mimeMessagePreparator});
    }

    default void send(MimeMessagePreparator... mimeMessagePreparators) throws MailException {
        try {
            List<MimeMessage> mimeMessages = new ArrayList<>(mimeMessagePreparators.length);
            for (MimeMessagePreparator preparator : mimeMessagePreparators) {
                MimeMessage mimeMessage = createMimeMessage();
                preparator.prepare(mimeMessage);
                mimeMessages.add(mimeMessage);
            }
            send(mimeMessages.toArray(new MimeMessage[0]));
        } catch (MailException ex) {
            throw ex;
        } catch (MessagingException ex) {
            throw new MailParseException(ex);
        } catch (Exception ex) {
            throw new MailPreparationException(ex);
        }
    }
}
